package com.douguo.recipe.network;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.Xml;

import com.douguo.recipe.RecipelistActivity;
import com.douguo.recipe.object.Caipu;

public class GetRecipeList {

	private static final String TAG = "GetRecipeList";

	public static void getCaipuList(int[] actions, String[] ids,
			String keywords, int offset, int count, final Handler handler) {
		final List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		int i = 0;
		if (actions != null) {
			for (int action : actions) {
				NameValuePair nvpAction = null;
				switch (action) {
				case Constant.TYPE_CAIXI:
					nvpAction = new BasicNameValuePair("caixi_id", ids[i]);
					break;
				case Constant.TYPE_CAIPIN:
					nvpAction = new BasicNameValuePair("caipin_id", ids[i]);
					break;
				case Constant.TYPE_KOUWEI:
					nvpAction = new BasicNameValuePair("kouwei_id", ids[i]);
					break;
				case Constant.TYPE_TESE:
					nvpAction = new BasicNameValuePair("tese_id", ids[i]);
					break;
				}
				i++;
				if (nvpAction != null)
					nvps.add(nvpAction);
			}
		}
		NameValuePair nvpOffset = new BasicNameValuePair("offset",
				String.valueOf(offset));
		NameValuePair nvpCount = new BasicNameValuePair("recipes_num",
				String.valueOf(count));
		nvps.add(nvpOffset);
		nvps.add(nvpCount);
		final String url;
		if (keywords != null) {
			url = Constant.URL_GET_SEARCH;
			nvps.add(new BasicNameValuePair("keywords", keywords));
		} else {
			url = Constant.URL_GET_RECIPE_LIST;
		}

		new Thread(new Runnable() {

			public void run() {
				DouguoConnection mConn = new DouguoConnection(url, nvps,
						mParseListener, DouguoConnection.GET_METHOD);
				List<Caipu> recipes = (List<Caipu>) mConn.Connect();
				handler.sendMessage(Message.obtain(handler,
						RecipelistActivity.MSG_UPDATE_LIST_FROM_NETWORK, recipes));

			}

		}).start();
	}

	private static OnParseListener mParseListener = new OnParseListener() {

		public Object onParsing(InputStream is) {
//			String source = "<?xml version=\"1.0\" encoding=\"utf-8\"?><response><recipes><recipe id=\"60380\"><name>海鳗五花肉砂锅煲 </name><thumbnail>http://img.douguo.com/upload/caiku/b/c/b/80_bcb18702d8442c3693b605439c28634b.jpg</thumbnail><author>东北的冬天特别冷</author><major>海鳗鱼 2条;五花肉 300克</major><minor>盐 适量;香叶 适量;老抽 适量;葱 适量;姜 适量;糖 适量;料酒 适量;蒜 适量;鸡精 适量;胡椒粉 适量;豆瓣酱 适量;麻油 适量;花椒 适量;辣椒 适量</minor></recipe><recipe id=\"60379\"><name>山寨中的战斗机——无敌潜艇堡 </name><thumbnail>http://img.douguo.com/upload/caiku/b/9/5/80_b9cb4d885950d1fd4db176504dcacd85.jpg</thumbnail><author>晨晨姐姐</author><major>培根 一包;12寸长面包 1个;鸡蛋 2个;生菜 100克</major><minor>肉松 40G;黄油 少许;盐 少许</minor></recipe><recipe id=\"60372\"><name>俗菜新做——香香脆脆咖喱鸡</name><thumbnail>http://img.douguo.com/upload/caiku/9/4/1/80_94bddeede555c3652395a95e03ba7f91.jpg</thumbnail><author>戴维斯</author><major>鸡腿 12只</major><minor>盐 2大匙;黄油 50g;咖喱粉 2大匙;白洋葱 1个</minor></recipe><recipe id=\"60355\"><name>豆花鱼火锅</name><thumbnail>http://img.douguo.com/upload/caiku/6/9/9/80_6921d91ae4933b24542de258c6c622a9.jpg</thumbnail><author>阿喜</author><major>豆花。草鱼 豆花1-2斤草鱼2斤左右;香料多种，四川豆瓣酱。花椒，胡椒，姜，葱，蒜，野山椒沙糖，芹菜 </major><minor></minor></recipe><recipe id=\"60338\"><name>腐乳汁烧油菜</name><thumbnail>http://img.douguo.com/upload/caiku/d/f/d/80_dfff7bcc19538d61e4324a67cc8cd86d.jpg</thumbnail><author>姜彡氺</author><major>油菜 若干;腐乳 2块加汁</major><minor>盐 少许;葱 3片;淀粉 少许</minor></recipe><recipe id=\"60252\"><name>麻辣香锅鱼88</name><thumbnail>http://img.douguo.com/upload/caiku/b/4/8/80_b4e555ac6690568c7c8023189b90bf08.jpg</thumbnail><author>*~LAZY貓儿~*----De快乐生活</author><major>洋芋 2小个;洋葱 1小个;莲藕 1小节;花鲢、江团鱼、黑鱼、乌江鱼 选其一;安龙二块粑 1/2个;黄瓜 1根;花菜和西兰花 各5个</major><minor>葱节 适量;香菜 4根;姜片 10片;食盐、味精、酱油 适量;烧烤汁 半小碗;孜然粉 2小勺;红黑花椒 各20粒;贵州特有的干辣椒 10个;萝卜条 适量</minor></recipe><recipe id=\"60214\"><name>金沙玉米</name><thumbnail>http://img.douguo.com/upload/caiku/e/2/9/80_e2235eca7008f28eba8e88d74ee30509.jpg</thumbnail><author>简单、平淡._Sweetゝ</author><major>玉米粒 300克;咸蛋黄 3个</major><minor>淀粉 100克左右;料酒 2茶匙（10ml）;油 适量</minor></recipe><recipe id=\"60204\"><name>清肠塑身美味佳肴——杂果疏菜煲</name><thumbnail>http://img.douguo.com/upload/caiku/2/8/c/80_2897fc8e121e6bb5c6e966de8850591c.jpg</thumbnail><author>异族极限</author><major>苹果 半个;胡萝卜 半根;白菜叶 半棵;火龙果 半个;梨 半个</major><minor>水 若干;橄榄油 3ML</minor></recipe><recipe id=\"60187\"><name>可乐鸡翅</name><thumbnail>http://img.douguo.com/upload/caiku/b/3/e/80_b395da6a793cdd8e9e8d9b3aa5921ace.jpg</thumbnail><author>小星星</author><major>鸡中翅 适量,约一盘;可口可乐 一罐;干红辣椒 适量</major><minor>葱 根据个人口味放;姜 根据个人口味放;花椒 根据个人口味放</minor></recipe><recipe id=\"60185\"><name>豆角炖粉条</name><thumbnail>http://img.douguo.com/upload/caiku/1/4/4/80_14258a58715128abae1cb7d513da1ef4.jpg</thumbnail><author>带刺青瓜</author><major>豆角 ;猪肉或排骨 ;木耳 ;宽粉条 </major><minor>酱油 ;大酱 ;花椒 ;八角 </minor></recipe>		</recipes></response>";
//			ByteArrayInputStream bais = new ByteArrayInputStream(source.getBytes());
//			BufferedInputStream bis = new BufferedInputStream(is);
//			int i = -1;
//			StringBuilder sb = new StringBuilder();
//			try {
//				while((i=bis.read())!=-1){
//					sb.append((char)i);
//				}
//				String str = new String(sb.toString().getBytes(),"UTF-8");
//				Log.d(TAG, str);
//			} catch (IOException e1) {
//				// TODO Auto-generated catch block
//				e1.printStackTrace();
//			}
			List<Caipu> recipes = null;
			XmlPullParser parser = Xml.newPullParser();
			Caipu currentCaipu = null;
			boolean done = false;

			try {

				parser.setInput(is, null);
				int eventType = parser.getEventType();
				while (eventType != XmlPullParser.END_DOCUMENT && !done) {
					String name = null;
					switch (eventType) {
					case XmlPullParser.START_DOCUMENT:
						recipes = new ArrayList<Caipu>();
						break;
					case XmlPullParser.START_TAG:
						name = parser.getName();
						if (name.equalsIgnoreCase("recipe")) {
							currentCaipu = new Caipu();
							currentCaipu.id = parser.getAttributeValue(null,
									"id");
						} else if (currentCaipu != null) {
							if (name.equalsIgnoreCase("name")) {
								currentCaipu.name = parser.nextText();
							} else if (name.equalsIgnoreCase("thumbnail")) {
								currentCaipu.thumbPath = parser.nextText();
							} else if (name.equalsIgnoreCase("author")) {
								currentCaipu.author = parser.nextText();
							} else if (name.equalsIgnoreCase("major")) {
								currentCaipu.major = parser.nextText();
							} else if (name.equalsIgnoreCase("minor")) {
								currentCaipu.minor = parser.nextText();
							}

						}
						break;
					case XmlPullParser.END_TAG:
						name = parser.getName();
						if (name.equalsIgnoreCase("recipe")
								&& currentCaipu != null) {
							recipes.add(currentCaipu);
						}
						break;
					case XmlPullParser.END_DOCUMENT:
						done = true;
						break;
					}
					eventType = parser.next();
				}
			} catch (XmlPullParserException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return recipes;
		}

	};

}
